from langchain_core.tools import StructuredTool
import uiautomator2 as u2
from simulators.mumu_control import MuMuControl

sim_ctl = MuMuControl()


def get_all_simulator_devices_info(*args, **kwargs) -> list:
    """获取当前电脑上所有 MuMu 模拟器的设备信息。"""
    return sim_ctl.show_all_device_info()


def get_package_name_by_app_name(app_name: str) -> str:
    """根据应用中文名称获取其包名。"""
    package_map = {
        "小小帝国": "com.camelgames.hogwarts",
        "微信": "com.tencent.mm",
        "抖音": "com.ss.android.ugc.aweme",
    }
    if app_name not in package_map:
        raise KeyError(f"未找到应用 '{app_name}' 的包名")
    return package_map[app_name]


def start_app(package_name: str, adb_host_ip: str, adb_port: int) -> bool:
    """在指定的 Android 模拟器上启动指定的应用。"""
    try:
        client = u2.connect(f"{adb_host_ip}:{adb_port}")
    except Exception as e:
        raise ConnectionError(f"无法连接到模拟器 {adb_host_ip}:{adb_port}，错误: {e}")

    try:
        client.app_stop(package_name)
        client.app_start(package_name, ".MainActivity")
    except Exception as e:
        raise RuntimeError(f"启动应用 {package_name} 失败: {e}")

    return True


tools = [
    StructuredTool.from_function(
        name="get_all_simulator_devices_info",
        func=get_all_simulator_devices_info,
        description="获取当前电脑上所有 MuMu 模拟器的设备信息。",
    ),
    StructuredTool.from_function(
        name="get_package_name_by_app_name",
        func=get_package_name_by_app_name,
        description="根据中文应用名获取其包名。例如：'小小帝国' -> 'com.camelgames.hogwarts'。",
    ),
    StructuredTool.from_function(
        name="start_app",
        func=start_app,
        description="在指定的 Android 模拟器上启动指定的应用。",
        parameters={  # ✅ 必须包含 "type": "object"
            "type": "object",
            "properties": {
                "package_name": {
                    "type": "string",
                    "description": "目标应用包名，例如 'com.tencent.mm'"
                },
                "adb_host_ip": {
                    "type": "string",
                    "description": "模拟器 ADB 主机 IP，例如 '127.0.0.1'"
                },
                "adb_port": {
                    "type": "integer",
                    "description": "模拟器 ADB 端口号，例如 7555"
                }
            },
            "required": ["package_name", "adb_host_ip", "adb_port"]
        },
    ),
]
